<template>
  <div class="admin-user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <el-button type="primary" @click="refreshUsers">刷新列表</el-button>
        </div>
      </template>

      <el-table :data="users" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="role" label="角色" width="150">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">{{ getRoleText(row.role) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="电话" width="150" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEditRole(row)"
            >
              修改角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 修改角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改用户角色"
      width="30%"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <span>{{ editForm.username }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateRole">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const users = ref([])
const dialogVisible = ref(false)
const editForm = ref({
  id: null,
  username: '',
  role: ''
})

const roleOptions = [
  { value: 'admin', label: '系统管理员' },
  { value: 'purchaser', label: '采购员' },
  { value: 'salesman', label: '销售员' },
  { value: 'deliveryman', label: '配送员' },
  { value: 'customer', label: '客户' }
]

const getRoleType = (role) => {
  const types = {
    admin: 'danger',
    purchaser: 'warning',
    salesman: 'success',
    deliveryman: 'info',
    customer: ''
  }
  return types[role] || ''
}

const getRoleText = (role) => {
  const texts = {
    admin: '系统管理员',
    purchaser: '采购员',
    salesman: '销售员',
    deliveryman: '配送员',
    customer: '客户'
  }
  return texts[role] || role
}

// 获取用户列表
const refreshUsers = async () => {
  try {
    console.log('Fetching users...');
    const response = await request.get('/api/users/get_users/');
    console.log('API Response:', response);
    users.value = response;
    console.log('Updated users value:', users.value);
  } catch (error) {
    console.error('Error fetching users:', error);
    console.error('Error details:', error.response?.data);
    ElMessage.error('获取用户列表失败');
  }
}

// 打开编辑角色对话框
const handleEditRole = (user) => {
  editForm.value = {
    id: user.id,
    username: user.username,
    role: user.role
  }
  dialogVisible.value = true
}

// 更新用户角色
const handleUpdateRole = async () => {
  try {
    await request.put(`/api/users/${editForm.value.id}/update_user_role/`, {
      role: editForm.value.role
    })
    ElMessage.success('角色更新成功')
    dialogVisible.value = false
    refreshUsers()
  } catch (error) {
    ElMessage.error('角色更新失败')
  }
}

onMounted(() => {
  refreshUsers()
})
</script>

<style scoped>
.admin-user-management {
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 